<template>
  <div class="stay-info-container ">
    <div class="handle-content-box">
      <div class="handle-content scroll-box">
        <div>
          <div class="add-name-box">
            <span class="app-form-red">*</span>
            <span class="add-name-text">处理说明</span>
          </div>
          <van-field
            v-model="handleExplain"
            type="textarea"
            placeholder="请输入"
            rows="1"
            autosize
            maxlength="100"
            :error-message="handleExplainError"
          />
        </div>
        <template v-if="orderType===2&&assocPlanList.length>0">
          <div class="associated-box">
            <div>
              <div class="associated-top-text">
                <span class="add-name-text top-name-text">关联保养计划</span>
                <van-switch
                  v-model="associatedSwitch"
                  size="24px"
                />
              </div>
            </div>
          </div>
          <template v-if="associatedSwitch">
            <div>
              <van-field
                readonly
                v-model="assocName"
                placeholder="请选择"
                right-icon="arrow"
                :error-message="assocNameError"
                @click="onOpenVar"
              />
            </div>
            <div>
              <div class="add-name-box">
                <span class="add-name-text">变量名称</span>
              </div>
              <van-field
                v-model="handleName"
                placeholder="自动获取"
                disabled
              />
            </div>
            <div>
              <div class="add-name-box">
                <span class="add-name-text">变化方向</span>
              </div>
              <van-field
                v-model="handleDirection"
                placeholder="自动获取"
                disabled
              />
            </div>
            <div>
              <div class="add-name-box">
                <span class="app-form-red">*</span>
                <span class="add-name-text">保养值</span>
              </div>
              <van-field
                v-model="handleMaintain"
                placeholder="请输入"
                type="number"
                :error-message="handleMaintainError"
              />
            </div>
            <div>
              <div class="add-name-box">
                <span class="app-form-red">*</span>
                <span class="add-name-text">周期阈值</span>
              </div>
              <van-field
                v-model="handleCycle"
                placeholder="请输入"
                type="number"
                :error-message="handleCycleError"
              />
            </div>
          </template>
        </template>

        <div class="parts-box">
          <div class="handle-parts-box">
            <span class="add-name-text">配件清单</span>
            <p
              class="all-delete color-primary"
              @click="onAllDeleteAcces()"
            >全部清空</p>
          </div>
          <div class="parts-all">
            <div
              class="single-acces"
              v-for="(item, index) in chooseVarDataMany"
              :key="index"
            >
              <div>
                <p class="parts-name-text">{{item.name}}</p>
                <p class="parts-id-text">编号：{{item.number}}</p>
              </div>
              <div>
                <van-stepper
                  v-model="item.accessoryCount"
                  min="0"
                  @minus="onPartsMinus(index)"
                />
              </div>
            </div>

            <van-button
              plain
              type="info"
              size="small"
              @click="onOpenVarMany"
            >选择配件</van-button>
          </div>

        </div>

      </div>
      <div class="parts-button-margin">
        <van-button
          block
          type="info"
          @click="submitHandle"
        >确 定</van-button>
      </div>
    </div>

    <!-- 配件 -->
    <van-popup
      v-model="showVarBoxMany"
      position="bottom"
      :close-on-click-overlay="false"
      :style="{ height: '64%' }"
    >
      <div class="var-box">
        <div class="var-box-header">
          <span class="model-name">{{ deviceModelNameMany || '' }}</span>
          <p class="model-choose">已选择（<span class="color-primary">{{ chooseVarDataMany.length }}</span>/{{filterVarListMany.length}}）</p>
        </div>
        <div class="var-search-box">
          <form action="/">
            <van-search
              v-model="searchKeyMany"
              shape="round"
              placeholder="搜索配件名称"
              clearable
              @search="handleSearchMany"
              @clear="handleClearMany"
            />
          </form>
        </div>
        <ul class="var-list scroll-box">
          <li
            v-for="(item, index) in filterVarListMany"
            :key="item.id"
            :class="{'color-primary': item.checked}"
            @click="selectVarMany(item, index)"
          >
            <span>{{ item.name}}</span>
            <van-icon
              name="success"
              v-if="item.checked"
            />
          </li>
        </ul>
        <ul class="operate-box">
          <li @click="cancelSelectMany">取消</li>
          <li
            class="color-primary"
            @click="confirmSelectMany"
          >确定</li>
        </ul>
      </div>
    </van-popup>
    <!-- 保养计划 -->
    <van-popup
      v-model="showVarBox"
      position="bottom"
      :close-on-click-overlay="false"
      :style="{ height: '64%' }"
    >
      <div class="var-box">
        <div class="var-box-header">
          <span class="model-name">{{ deviceModelName || '' }}</span>
          <!-- <p class="model-choose">已选择（<span class="color-primary">{{ chooseVarData.length }}</span>/5）</p> -->
        </div>
        <div class="var-search-box">
          <form action="/">
            <van-search
              v-model="searchKey"
              shape="round"
              placeholder="搜索保养计划名称"
              clearable
              @search="handleSearch"
              @clear="handleClear"
            />
          </form>
        </div>
        <ul class="var-list scroll-box">
          <li
            v-for="(item, index) in assocPlanList"
            :key="item.id"
            :class="{'color-primary': item.checked}"
            @click="selectVar(item, index)"
          >
            <span>{{ item.name}}</span>
            <van-icon
              name="success"
              v-if="item.checked"
            />
          </li>
        </ul>
        <ul class="operate-box">
          <li @click="cancelSelect">取消</li>
          <li
            class="color-primary"
            @click="confirmSelect"
          >确定</li>
        </ul>
      </div>
    </van-popup>
  </div>

</template>

<script>
import { Button, Dialog, Field, Stepper, Popup, Search, Toast, Switch } from 'vant';
import { getModelAccessories, completeOrder, getPlanList } from '@/api/maintenanceEngineer';
export default {
  name: 'StayWorkDetail',
  components: {
    [Button.name]: Button,
    [Dialog.Component.name]: Dialog.Component,
    [Field.name]: Field,
    [Stepper.name]: Stepper,
    [Popup.name]: Popup, //弹窗
    [Search.name]: Search, //搜索
    [Toast.name]: Toast, //提示
    [Switch.name]: Switch //开关
  },
  data() {
    return {
      handleExplain: '', //处理说明
      handleExplainError: '',
      associatedSwitch: this.sourceHandle === 2 ? true : false, //关联保养计划
      assocPlanList: [], //关联保养计划数据
      handleName: '', //变量名称
      handleDirection: '', //变化方向
      handleMaintain: '', //保养值
      handleMaintainError: '',
      handleCycle: '', //周期阈值
      handleCycleError: '',
      showVarBoxMany: false, //打开多选择弹窗
      searchKeyMany: '', //多选择框搜索
      varTotalMany: 0, //多选择框总数
      varListMany: [], //多选择框全部数据
      filterVarListMany: [],
      deviceModelNameMany: '选择配件', //选择框搜索标题
      chooseVarDataMany: [], //多选择选中
      openBeforeMany: [], //打开选择框之前选中的值
      assocName: '', //保养计划名称
      assocNameError: '',
      assocId: '', //保养计划id
      showVarBox: false, //打开选择弹窗
      searchKey: '', //选择框搜索
      varTotal: 0, //总数
      varList: [], //全部数据
      filterVarList: [],
      deviceModelName: '选择保养计划', //选择框搜索标题
      chooseVarData: [],
      openBefore: []
    };
  },
  props: ['deviceModelId', 'orderType', 'sourceHandle'],
  mounted() {
    this.onAssocPlanList();
  },
  methods: {
    //选择配件
    //配件数据
    onModelAccessories() {
      getModelAccessories({ id: this.deviceModelId }).then(res => {
        this.varListMany = res.data;
        this.varListMany.map(item => {
          item.checked = false;
          item.accessoryCount = 1;
        });
        //回显勾选
        if (this.chooseVarDataMany.length) {
          this.chooseVarDataMany.map(item => {
            this.varListMany.map(subItem => {
              if (subItem.id === item.id) {
                subItem.checked = true;
              }
            });
          });
        }
        this.filterVarListMany = this.varListMany;
      });
    },
    //打开
    onOpenVarMany() {
      this.showVarBoxMany = true;
      this.openBeforeMany = JSON.parse(JSON.stringify(this.chooseVarDataMany));
      this.searchKeyMany = '';
      this.onModelAccessories();
    },
    // 搜索变量
    handleSearchMany() {
      let filterArrMany = this.varListMany.filter(item => {
        return item.name.indexOf(this.searchKeyMany) !== -1;
      });
      this.filterVarListMany = filterArrMany;
    },
    // 清空搜索
    handleClearMany() {
      this.filterVarListMany = this.varListMany;
    },
    // 删除所选抄送人员
    deleteVarDataMany(index) {
      this.chooseVarDataMany.splice(index, 1);
    },
    // 选择变量
    selectVarMany(item, index) {
      item.checked = !item.checked;
      this.$forceUpdate();
      if (item.checked) {
        this.chooseVarDataMany.push(item);
      } else {
        this.chooseVarDataMany.map((chooseItem, index) => {
          if (item.id === chooseItem.id) {
            this.chooseVarDataMany.splice(index, 1);
          }
        });
      }
    },
    // 取消变量选择
    cancelSelectMany() {
      this.showVarBoxMany = false;
      this.chooseVarDataMany = this.openBeforeMany;
    },
    // 确定变量选择
    confirmSelectMany() {
      if (this.chooseVarDataMany.length === 0) {
        this.showVarBoxMany = false;
        this.$forceUpdate();
        return;
      }
      this.showVarBoxMany = false;
    },

    //选择关联保养计划
    //获取关联保养计划
    onAssocPlanList() {
      let pram = {
        mode: 2,
        modelId: this.deviceModelId
      };
      getPlanList(pram).then(res => {
        this.varList = res.data.list;
        let planIdArr = [];
        this.varList.map((item, indexi) => {
          planIdArr.push(item.id); //保养计划id
          if (indexi === 0) {
            item.checked = true;
          } else {
            item.checked = false;
          }
        });

        //maintain_plan_id存在于保养计划id 开关就是开的，反之就是关的
        if (planIdArr.includes(parseInt(this.$route.query.planId))) {
          this.associatedSwitch = true;
        } else {
          this.associatedSwitch = false;
        }

        this.assocPlanList = this.varList;
        if (this.chooseVarData.length === 0) {
          this.chooseVarData.push(this.varList[0]);
          this.assocName = this.varList[0].name;
          this.assocId = this.varList[0].id;
          this.handleName = this.varList[0].vname;
          this.handleDirection = this.varList[0].directionChange === 1 ? '递增' : '递减';
          this.handleMaintain = '';
          this.handleCycle = this.varList[0].threshold;
        }
      });
    },

    //打开
    onOpenVar() {
      this.showVarBox = true;
      //回显勾选
      if (this.chooseVarData.length) {
        this.chooseVarData.map(item => {
          this.varList.map(subItem => {
            if (subItem.id === item.id) {
              subItem.checked = true;
            } else {
              subItem.checked = false;
            }
          });
        });
      }
      // this.searchKey = '';
      this.assocPlanList = this.varList;
      this.openBefore = JSON.parse(JSON.stringify(this.chooseVarData));
    },
    // 搜索变量
    handleSearch() {
      let filterArr = this.varList.filter(item => {
        return item.name.indexOf(this.searchKey) !== -1;
      });
      this.assocPlanList = filterArr;
    },
    // 清空搜索
    handleClear() {
      this.assocPlanList = this.varList;
    },
    // 选择变量
    selectVar(item, index) {
      this.chooseVarData = [];
      if (!item.checked) {
        this.assocPlanList.map((fitem, findex) => {
          if (index === findex) {
            fitem.checked = true;
          } else {
            fitem.checked = false;
          }
        });
        this.$forceUpdate();
        this.chooseVarData.push(item);
      } else {
        item.checked = false;
        this.$forceUpdate();
      }
    },
    // 取消变量选择
    cancelSelect() {
      this.showVarBox = false;
      this.chooseVarData = this.openBefore;
    },
    // 确定变量选择
    confirmSelect() {
      if (this.chooseVarData.length === 0) {
        this.assocName = '';
        this.assocId = '';
        this.handleName = '';
        this.handleDirection = '';
        this.handleMaintain = '';
        this.handleCycle = '';
        this.showVarBox = false;
        this.$forceUpdate();
        return;
      } else {
        this.assocName = this.chooseVarData[0].name;
        this.assocId = this.chooseVarData[0].id;
        this.handleName = this.chooseVarData[0].vname;
        this.handleDirection = this.chooseVarData[0].directionChange === 1 ? '递增' : '递减';
        this.handleMaintain = '';
        this.handleCycle = this.chooseVarData[0].threshold;
        this.showVarBox = false;
      }
    },

    //处理工单
    submitHandle() {
      this.handleExplainError = '';
      this.assocNameError = '';
      this.handleMaintainError = '';
      this.handleCycleError = '';
      if (this.handleExplain === '') {
        this.handleExplainError = '请输入处理说明';
        return;
      }
      if (this.associatedSwitch && this.assocName === '') {
        this.assocNameError = '请选择保养计划';
        return;
      }
      if (this.associatedSwitch && this.handleMaintain === '') {
        this.handleMaintainError = '请输入保养值';
        return;
      }
      if (this.associatedSwitch && this.handleCycle === '') {
        this.handleCycleError = '请输入周期阈值';
        return;
      }
      let params = {};
      params.processing_result = this.handleExplain;
      params.id = parseInt(this.$route.query.id);
      params.accessory_list = [];
      this.chooseVarDataMany.forEach(item => {
        let temp = {};
        temp.name = item.name;
        temp.id = item.accessoriesId;
        temp.num = item.accessoryCount;
        temp.number = item.number;
        params.accessory_list.push(temp);
      });
      //保养工单
      if (this.orderType === 2 && this.associatedSwitch) {
        params.is_relate_plan = this.associatedSwitch ? '1' : '2';
        params.currentValue = parseFloat(this.handleMaintain);
        params.threshold = parseFloat(this.handleCycle);
        params.maintain_plan = this.assocName;
        params.maintain_plan_id = parseInt(this.assocId);
        params.vname = this.handleName;
      }
      if (!this.associatedSwitch) {
        params.is_relate_plan = '2';
      }
      params.accessory_list = JSON.stringify(params.accessory_list);
      completeOrder(params).then(res => {
        Toast('处理工单成功');
        this.$emit('handleSub', true);
      });
    },
    //工单处理-清空配件
    onAllDeleteAcces() {
      Dialog.confirm({
        title: '提示',
        confirmButtonText: '确认',
        confirmButtonColor: '#3378FF',
        cancelButtonText: '取消',
        message: '确定清空全部配件？'
      })
        .then(() => {
          this.chooseVarDataMany = [];
        })
        .catch(() => {
          // on cancel
        });
    },
    //工单处理-单个删除配件
    onPartsMinus(index) {
      Dialog.confirm({
        title: '提示',
        confirmButtonText: '确认',
        confirmButtonColor: '#3378FF',
        cancelButtonText: '取消',
        message: '配件数量减少到0将删除此配件，你确定删除此配件？'
      })
        .then(() => {
          this.chooseVarDataMany.splice(index, 1);
        })
        .catch(() => {
          // on cancel
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.stay-info-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

//工单处理
.handle-content-box {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  background-color: #fff;
  margin-top: 0.213333rem;
}
.handle-content {
  flex: 1;
  padding-bottom: 0.213333rem;
}
.app-form-red {
  color: #f56c6c;
  font-size: 0.32rem;
}
.add-name-box {
  margin-left: 0.426667rem;
}
.add-name-text {
  color: #666666;
  font-size: 0.32rem;
}
.parts-box {
  padding: 0.213333rem 0.426667rem;
  margin-top: 0.213333rem;
}
.handle-parts-box {
  display: flex;
  justify-content: space-between;
}
.all-delete {
  font-size: 0.32rem;
}
.parts-all {
  padding-top: 0.426667rem;
}
.single-acces {
  display: flex;
  justify-content: space-between;
  margin-bottom: 0.426667rem;
}
.parts-name-text {
  font-size: 0.373333rem;
}
.parts-id-text {
  font-size: 0.32rem;
  color: #999999;
  margin-top: 0.266667rem;
}
//关联保养计划
.associated-box {
  padding: 0rem 0.426667rem 0rem 0.426667rem;
  .associated-top-text {
    display: flex;
    justify-content: space-between;
    margin-top: 0.213333rem;
  }
  .top-name-text {
    margin-top: 0.213333rem;
  }
}

//工单处理确定按钮
.parts-button-margin {
  flex-shrink: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 1.92rem;
  padding: 0 0.426667rem;
  background-color: #fff;
  border-top: 1px solid #f2f6fc;
}

::v-deep .van-field__value {
  border-bottom: 1px solid #f2f6fc;
  padding: 0.133333rem 0;
}
//选择设备搜索框
::v-deep .var-search-box .van-field__value {
  padding: 0;
}
::v-deep .van-button {
  border-radius: 0.106667rem;
}

//选择器
.van-popup--bottom {
  border-top-left-radius: 0.426667rem;
  border-top-right-radius: 0.426667rem;

  .var-box {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;

    .var-box-header {
      flex-shrink: 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 0.213333rem;
      padding: 0 0.426667rem;
      padding-top: 0.426667rem;

      .model-name {
        margin-right: 0.266667rem;
        font-size: 0.426667rem;
        line-height: 0.533333rem;
      }

      .model-choose {
        flex-shrink: 0;
        color: var(--color-deep-gary);
        font-size: 0.32rem;
      }
    }

    .var-search-box {
      flex-shrink: 0;
      margin-bottom: 0.213333rem;
      border-bottom: 1px solid var(--border-color);
    }

    .var-list {
      flex: 1;
      width: 100%;
      padding: 0 0.426667rem;

      li {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0.32rem 0;
        font-size: 0.373333rem;
        border-bottom: 1px solid var(--border-color);

        &:last-of-type {
          border-bottom: 0;
        }
      }
    }

    .operate-box {
      flex-shrink: 0;
      display: flex;
      width: 100%;
      height: 1.28rem;
      border-top: 1px solid var(--border-color);

      li {
        position: relative;
        display: flex;
        justify-content: center;
        align-items: center;
        width: 50%;
        font-size: 0.426667rem;

        &:first-of-type {
          &::after {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            width: 1px;
            height: 100%;
            background-color: var(--border-color);
          }
        }
      }
    }
  }
}
</style>